<template>
  <div class="diet-plan-container">
    <!-- 生成计划区域 -->
    <el-card class="generation-card" v-if="!currentPlan">
      <template #header>
        <div class="card-header">
          <h2>生成个性化饮食计划</h2>
          <p class="subtitle">基于您的身体指标和健身目标，为您量身定制饮食计划</p>
        </div>
      </template>

      <el-form :model="generationForm" label-width="120px" class="generation-form">
        <el-form-item label="计划天数">
          <el-input-number
            v-model="generationForm.days"
            :min="1"
            :max="30"
            style="width: 200px"
          />
          <span class="form-tip">天（建议7-14天）</span>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="generatePlan" 
            :loading="generating"
            size="large"
            :disabled="!hasUserProfile"
          >
            {{ hasUserProfile ? '生成饮食计划' : '请先完善个人信息' }}
          </el-button>
          <el-button 
            v-if="!hasUserProfile" 
            @click="goToProfile" 
            size="large"
          >
            去完善信息
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 饮食计划展示区域 -->
    <div v-if="currentPlan" class="plan-display">
      <!-- 计划概览 -->
      <el-card class="plan-overview">
        <template #header>
          <div class="overview-header">
            <h2>您的饮食计划</h2>
            <div class="overview-actions">
              <el-button @click="currentPlan = null" size="small">生成新计划</el-button>
              <el-button type="primary" @click="savePlan" size="small">保存计划</el-button>
            </div>
          </div>
        </template>

        <div class="plan-summary">
          <el-row :gutter="24">
            <el-col :span="6">
              <div class="summary-item calories-item">
                <div class="summary-icon">
                  <el-icon size="30"><Lightning /></el-icon>
                </div>
                <div class="summary-content">
                  <div class="summary-value">{{ currentPlan.total_calories }}</div>
                  <div class="summary-label">每日卡路里</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item days-item">
                <div class="summary-icon">
                  <el-icon size="30"><Calendar /></el-icon>
                </div>
                <div class="summary-content">
                  <div class="summary-value">{{ currentPlan.daily_meals.length }}</div>
                  <div class="summary-label">计划天数</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item strategy-item">
                <div class="summary-icon">
                  <el-icon size="30"><TrophyBase /></el-icon>
                </div>
                <div class="summary-content">
                  <div class="summary-value strategy-name">{{ getStrategyName(currentPlan.strategy_used) }}</div>
                  <div class="summary-label">推荐策略</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item date-item">
                <div class="summary-icon">
                  <el-icon size="30"><Clock /></el-icon>
                </div>
                <div class="summary-content">
                  <div class="summary-value">{{ formatDate(currentPlan.start_date) }}</div>
                  <div class="summary-label">开始日期</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 每日饮食详情 -->
      <div class="daily-meals">
        <el-card 
          v-for="(dailyMeal, index) in currentPlan.daily_meals" 
          :key="index"
          class="daily-meal-card"
        >
          <template #header>
            <div class="meal-header">
              <h3>第 {{ index + 1 }} 天 - {{ formatDate(dailyMeal.date) }}</h3>
              <el-tag type="success">{{ getDayOfWeek(dailyMeal.date) }}</el-tag>
            </div>
          </template>

          <div class="meals-grid">
            <!-- 早餐 -->
            <div class="meal-section">
              <div class="meal-title">
                <el-icon><Sunny /></el-icon>
                <span>早餐</span>
              </div>
              <div class="meal-foods">
                <div 
                  v-for="food in dailyMeal.breakfast" 
                  :key="food.id"
                  class="food-item"
                >
                  <div class="food-name">{{ food.name }}</div>
                  <div class="food-nutrition">
                    <span class="calories">{{ food.calories }}卡</span>
                    <span class="protein">蛋白质: {{ food.protein }}g</span>
                    <span class="carbs">碳水: {{ food.carbs }}g</span>
                    <span class="fat">脂肪: {{ food.fat }}g</span>
                  </div>
                </div>
                <div v-if="dailyMeal.breakfast.length === 0" class="no-food">
                  暂无推荐食物
                </div>
              </div>
            </div>

            <!-- 午餐 -->
            <div class="meal-section">
              <div class="meal-title">
                <el-icon><Sunrise /></el-icon>
                <span>午餐</span>
              </div>
              <div class="meal-foods">
                <div 
                  v-for="food in dailyMeal.lunch" 
                  :key="food.id"
                  class="food-item"
                >
                  <div class="food-name">{{ food.name }}</div>
                  <div class="food-nutrition">
                    <span class="calories">{{ food.calories }}卡</span>
                    <span class="protein">蛋白质: {{ food.protein }}g</span>
                    <span class="carbs">碳水: {{ food.carbs }}g</span>
                    <span class="fat">脂肪: {{ food.fat }}g</span>
                  </div>
                </div>
                <div v-if="dailyMeal.lunch.length === 0" class="no-food">
                  暂无推荐食物
                </div>
              </div>
            </div>

            <!-- 晚餐 -->
            <div class="meal-section">
              <div class="meal-title">
                <el-icon><Moon /></el-icon>
                <span>晚餐</span>
              </div>
              <div class="meal-foods">
                <div 
                  v-for="food in dailyMeal.dinner" 
                  :key="food.id"
                  class="food-item"
                >
                  <div class="food-name">{{ food.name }}</div>
                  <div class="food-nutrition">
                    <span class="calories">{{ food.calories }}卡</span>
                    <span class="protein">蛋白质: {{ food.protein }}g</span>
                    <span class="carbs">碳水: {{ food.carbs }}g</span>
                    <span class="fat">脂肪: {{ food.fat }}g</span>
                  </div>
                </div>
                <div v-if="dailyMeal.dinner.length === 0" class="no-food">
                  暂无推荐食物
                </div>
              </div>
            </div>

            <!-- 零食 -->
            <div class="meal-section">
              <div class="meal-title">
                <el-icon><Food /></el-icon>
                <span>零食</span>
              </div>
              <div class="meal-foods">
                <div 
                  v-for="food in dailyMeal.snacks" 
                  :key="food.id"
                  class="food-item"
                >
                  <div class="food-name">{{ food.name }}</div>
                  <div class="food-nutrition">
                    <span class="calories">{{ food.calories }}卡</span>
                    <span class="protein">蛋白质: {{ food.protein }}g</span>
                    <span class="carbs">碳水: {{ food.carbs }}g</span>
                    <span class="fat">脂肪: {{ food.fat }}g</span>
                  </div>
                </div>
                <div v-if="dailyMeal.snacks.length === 0" class="no-food">
                  暂无推荐食物
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Sunny, Sunrise, Moon, Food, Lightning, Calendar, TrophyBase, Clock } from '@element-plus/icons-vue'
import { dietAPI } from '@/api/index'

const router = useRouter()

// 响应式数据
const currentPlan = ref(null)
const generating = ref(false)
const hasUserProfile = ref(false)

// 生成表单
const generationForm = reactive({
  days: 7
})

// 从URL参数获取天数
const route = useRoute()
if (route.query.days) {
  generationForm.days = parseInt(route.query.days)
}

// 检查用户是否有档案信息
const checkUserProfile = async () => {
  try {
    const response = await dietAPI.getUserProfile()
    hasUserProfile.value = !!(response && response.height && response.weight)
  } catch (error) {
    console.error('检查用户档案失败:', error)
    hasUserProfile.value = false
  }
}

// 生成饮食计划
const generatePlan = async () => {
  try {
    generating.value = true
    
    const response = await dietAPI.generateDietPlan({
      days: generationForm.days
    })
    
    if (response) {
      currentPlan.value = response
      ElMessage.success('饮食计划生成成功！')
    }
  } catch (error) {
    console.error('生成饮食计划失败:', error)
    ElMessage.error('生成失败，请重试')
  } finally {
    generating.value = false
  }
}

// 保存计划
const savePlan = () => {
  ElMessage.success('计划已保存到历史记录')
}

// 跳转到个人信息页面
const goToProfile = () => {
  router.push('/collect-profile')
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取星期几
const getDayOfWeek = (dateString) => {
  const date = new Date(dateString)
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return days[date.getDay()]
}

// 获取策略中文名称
const getStrategyName = (strategy) => {
  const strategyMap = {
    'WeightLossVegetarian': '减脂素食',
    'MuscleGainHighProtein': '增肌高蛋白',
    'BalancedLowCarb': '均衡低碳水',
    'BalancedLowCa': '均衡低碳水' // 处理截断的策略名
  }
  return strategyMap[strategy] || strategy
}

// 组件挂载时检查用户档案
onMounted(() => {
  checkUserProfile()
})
</script>

<style scoped>
.diet-plan-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.generation-card {
  max-width: 600px;
  margin: 0 auto 20px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
}

.subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.generation-form {
  margin-top: 20px;
}

.form-tip {
  margin-left: 10px;
  color: #999;
  font-size: 14px;
}

.plan-display {
  max-width: 1200px;
  margin: 0 auto;
}

.plan-overview {
  margin-bottom: 20px;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-header h2 {
  margin: 0;
  color: #333;
}

.overview-actions {
  display: flex;
  gap: 10px;
}

.plan-summary {
  margin-top: 20px;
}

.summary-item {
  display: flex;
  align-items: center;
  padding: 24px;
  background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.summary-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.summary-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 16px;
  background: linear-gradient(145deg, #f0f2f5, #ffffff);
  box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.1);
}

.calories-item .summary-icon {
  background: linear-gradient(145deg, #fef7e6, #fff3cd);
  color: #e6a23c;
}

.days-item .summary-icon {
  background: linear-gradient(145deg, #e8f4fd, #d1ecf1);
  color: #409eff;
}

.strategy-item .summary-icon {
  background: linear-gradient(145deg, #f0f9e8, #e7f3d0);
  color: #67c23a;
}

.date-item .summary-icon {
  background: linear-gradient(145deg, #fef0f0, #fde2e2);
  color: #f56c6c;
}

.summary-content {
  flex: 1;
}

.summary-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 4px;
  background: linear-gradient(145deg, #333 0%, #555 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.strategy-name {
  font-size: 18px !important;
  font-weight: 600;
}

.summary-label {
  font-size: 13px;
  color: #8590a6;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.daily-meals {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.daily-meal-card {
  margin-bottom: 20px;
}

.meal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.meal-header h3 {
  margin: 0;
  color: #333;
}

.meals-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.meal-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.meal-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  font-size: 16px;
}

.meal-foods {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.food-item {
  background: white;
  border-radius: 6px;
  padding: 12px;
  border-left: 4px solid #409eff;
}

.food-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.food-nutrition {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 12px;
}

.calories {
  color: #e6a23c;
  font-weight: bold;
}

.protein {
  color: #67c23a;
}

.carbs {
  color: #409eff;
}

.fat {
  color: #f56c6c;
}

.no-food {
  text-align: center;
  color: #999;
  font-style: italic;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .diet-plan-container {
    padding: 10px;
  }
  
  .meals-grid {
    grid-template-columns: 1fr;
  }
  
  .overview-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .overview-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>
